<?php

namespace App\Common\HeatCache;

use App\Common\RedisCache\UserCache;
use App\Common\Utill\ElasticSearch;
use App\services\v1\UserServices;

class UserHeat
{
    /**
     * 获取用户信息
     * @param int $userId
     * @return array|mixed|\Redis|string
     * @throws \Exception
     */
    public static function getUserInfoById(int $userId)
    {
        $userCache = new UserCache();
        $userCache->setKeyParameter([$userId]);
        $userInfo  = $userCache->get();
        //热数据永不过期
        if ($userInfo) {
            $userCache->expire();
            return $userInfo;
        }
        //缓存没有从es获取
        $where = [
            'must' => [
                'term' => [
                    [
                        'id' => $userId
                    ]
                ],
            ],
        ];
        $userInfo = ElasticSearch::instance()->index('user_*')->where($where)->search();
        if ($userInfo['data']) {
            return $userInfo['data'][0] ?? [];
        }
        //如果es没数据 从数据库获取
        return (new UserServices())->getUserInfoById($userId);
    }
}